package io.renren.common.session;

import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Pool;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义ConnectionFactory，通过key路由到一个redis服务器
 * Created by luzhenting on 2017/11/27.
 */
public class SpringSessionConnectionFactory extends JedisConnectionFactory{

    private redis.clients.util.Pool<ShardedJedis> shardedJedisPool;

    public Pool<ShardedJedis> getShardedJedisPool() {
        return shardedJedisPool;
    }

    public void setShardedJedisPool(Pool<ShardedJedis> shardedJedisPool) {
        this.shardedJedisPool = shardedJedisPool;
    }

    public SpringSessionConnectionFactory(){}

    public SpringSessionConnectionFactory(JedisPoolConfig poolConfig, ClusterConfiguration clusterConfiguration){
        this.shardedJedisPool = new ShardedJedisPool(poolConfig,clusterConfiguration.getShards());
    }

    /**
     * 抓取对应的ShardedJedis
     * @return
     */
    public ShardedJedis fetchShardedJedis() {
        try {
            if ( shardedJedisPool != null ) {
                return shardedJedisPool.getResource();
            }
            List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
            shards.add(new JedisShardInfo("127.0.0.1",6379));
            ShardedJedis defult = new ShardedJedis(shards);
            return defult;
        } catch (Exception ex) {
            throw new RedisConnectionFailureException("Cannot get Jedis connection", ex);
        }
    }
}
